#!/usr/bin/env python2

#GoodFET SPI Flash Client
#by Travis Goodspeed

#N.B.,
#Might be Winbond W25x80-specific.

import sys;
import binascii;
import array;

from GoodFETSPI import GoodFETSPI25C;
from intelhex import IntelHex;

if(len(sys.argv)==1):
    print "Usage: %s verb [objects]\n" % sys.argv[0];
    print "%s info" % sys.argv[0];
    print "%s dump $foo.rom [0x$start 0x$stop]" % sys.argv[0];
    #print "%s erase" % sys.argv[0];
    #print "%s flash $foo.rom [0x$start 0x$stop]" % sys.argv[0];
    #print "%s verify $foo.rom [0x$start 0x$stop]" % sys.argv[0];
    print "%s peek 0x$start [0x$stop]" % sys.argv[0];
    #print "%s poke 0x$adr 0x$val" % sys.argv[0];
    sys.exit();

#Initialize FET and set baud rate
client=GoodFETSPI25C();
client.serInit()


client.SPIsetup();

#Dummy read.
#Might read as all ones if chip has a startup delay.

if(sys.argv[1]=="test"):
	for adr in range(0,32): #*1024):
            val=client.peek8(adr);
            print "%04x:=%02x" % (adr,val);
if(sys.argv[1]=="dump"):
    f = sys.argv[2];
    start=0x0000;
    stop=4*1024;
    if(len(sys.argv)>3):
        start=int(sys.argv[3],16);
    if(len(sys.argv)>4):
        stop=int(sys.argv[4],16);
    
    print "Dumping from %04x to %04x as %s." % (start,stop,f);
    h = IntelHex(None);
    i=start;
    while i<=stop:
        data=client.peek8(i);
        print "Dumped %04x=%02x."%(i,data);
        h[i]=data;
        i+=1;
    h.write_hex_file(f);

if(sys.argv[1]=="peek"):
    start=0x0000;
    if(len(sys.argv)>2):
        start=int(sys.argv[2],16);
    stop=start;
    if(len(sys.argv)>3):
        stop=int(sys.argv[3],16);
    print "Peeking from %04x to %04x." % (start,stop);
    while start<=stop:
        print "%04x: %02x" % (start,client.peek8(start));
        start=start+1;
